﻿

using FluentValidation;
using Masa.BuildingBlocks.Dispatcher.Events;
using Masa.CqrsProject.Commands;
using Masa.CqrsProject.Models;
using Masa.CqrsProject.Querys;
using Masa.CqrsProject.Services.Dtos;
using Microsoft.AspNetCore.Mvc;

namespace Masa.CqrsProject.Services
{
    
    /// <summary>
    /// 订单服务
    /// </summary>
    public class OrderService : ServiceBase
    {

        private IEventBus EventBus => GetRequiredService<IEventBus>();

        //private readonly IValidator<OrderInfo> _validator;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="validator"></param>
        public OrderService()
        {
        }

        /// <summary>
        /// 查询订单
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<OrderInfo> GetAsync([FromQuery]int id)
        {
            GetOrderInfoQuery query = new GetOrderInfoQuery() { id = id };
            await EventBus.PublishAsync(query);
            return query.Result;
        }

        /// <summary>
        /// 查询订单列表（读写分离）
        /// </summary>
        /// <returns></returns>
        [HttpGet("list")]
        public async Task<List<OrderInfo>> GetListAsync()
        {
            GetOrderListQuery query = new GetOrderListQuery();
            await EventBus.PublishAsync(query);
            return query.Result;
        }

        /// <summary>
        /// 创建订单
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> CreateAsync(CreateOrderCommand command)
        {
            await EventBus.PublishAsync(command);
            return "Success";
        }

        /// <summary>
        /// 更新订单
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        public async Task<string> UpdateAsync(UpdateOrderDto request)
        {
            UpdateOrderCommand command = new UpdateOrderCommand();
            command.Id = request.Id;
            command.OrderInfo = request.OrderInfo;   

            await EventBus.PublishAsync(command);
            return "Success";
        }

        /// <summary>
        /// 删除订单
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<string> DeleteAsync([FromBody] DeleteOrderCommand command)
        {
            await EventBus.PublishAsync(command);
            return "删除成功";

        }

    }
}
